package com.deep.order.interceptor;

import com.deep.common.model.constant.AuthConstant;
import com.deep.common.model.dto.MemberResponseVO;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * 用户登录拦截器
 *
 * @author Deep
 * @date 2022/2/14
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberResponseVO> loginUser = new ThreadLocal<>();

    /**
     * 方法执行前拦截（请求到达之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 路径匹配放行(用于为微服务间调用时不登陆也能放行)
        String uri = request.getRequestURI();
        AntPathMatcher matcher = new AntPathMatcher();
        boolean match = matcher.match("/order/order/status/**", uri);
        boolean match1 = matcher.match("/payed/notify", uri);
        if (match || match1) {
            return true;
        }

        // 登录拦截
        HttpSession session = request.getSession();
        MemberResponseVO attribute = (MemberResponseVO) session.getAttribute(AuthConstant.LOGIN_USER);
        if (attribute != null) {
            // 已登录
            loginUser.set(attribute);
            return true;
        } else {
            // 未登录，返回登录页面
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("<script>alert('请先进行登录，再进行后续操作!');location.href='http://auth.mall.com/api/auth/login.html'</script>");
//            session.setAttribute("message", "请先进行登录再进行后续操作!");
//            response.sendRedirect("http://localhost:14000/login.html");
            // 未登录(去登陆)
            return false;
        }
    }

    /**
     * 方法执行后拦截
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
}
